﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace psafth.RCTiming.Main
{
    public static class DatabaseHelper
    {
        private static Object dbLock = new Object();

        public static void DoWithDB<T>(Action<T> dbAction) where T : DbContext, new()
        {
            if (dbAction == null)
                throw new ArgumentNullException("dbAction");

            try
            {
                lock (dbLock)
                {
                    // Create the database context
                    using (T context = new T())
                    {
                        dbAction(context);
                    }
                }
            }
            catch (DbEntityValidationException dbEx)
            {
                List<string> errors = new List<string>();

                // Add to the list of validation errors
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                    foreach (var er in validationErrors.ValidationErrors)
                        errors.Add(string.Format("Error: (Property - {0}) {1}", er.PropertyName, er.ErrorMessage));

                throw new Exception(string.Format("Error when validating entities: {0}", string.Join(", ", errors)), dbEx);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static async Task DoWithDBAsync<T>(Action<T> dbAction) where T : DbContext, new()
        {
            if (dbAction == null)
                throw new ArgumentNullException("dbAction");

            try
            {

                // Create the database context
                using (T context = new T())
                {
                    await Task.Run(() =>
                    {
                        lock (dbLock)
                        {
                            dbAction(context);
                        }
                    });
                }
            }
            catch (DbEntityValidationException dbEx)
            {
                List<string> errors = new List<string>();

                // Add to the list of validation errors
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                    foreach (var er in validationErrors.ValidationErrors)
                        errors.Add(string.Format("Error: (Property - {0}) {1}", er.PropertyName, er.ErrorMessage));

                throw new Exception(string.Format("Error when validating entities: {0}", string.Join(", ", errors)), dbEx);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
